package com.demo.shiroDemo08.web;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class IndexController {

	@RequestMapping("/")
	public String index() {
		return "index";
	}

	@RequestMapping(value = "/login", method = { RequestMethod.GET })
	public String loginPage() {
		return "login";
	}

	@RequestMapping(value = "/login", method = { RequestMethod.POST })
	public String login(HttpServletRequest request, Model model) {
		String className = String.valueOf(request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME));
		if (UnknownAccountException.class.getName().equals(className)
				|| IncorrectCredentialsException.class.getName().endsWith(className)) {
			model.addAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME, "用户名/密码错误");
		} else if (AuthenticationException.class.getName().endsWith(className)) {
			model.addAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME, "其他错误");
		}
		return "login";
	}

	@RequestMapping("/site")
	@ResponseBody
	public Object site() {
		Map<String, Object> map = new HashMap<>();
		map.put("name", "shiroDemos");
		map.put("time", new Date());
		return map;
	}

}
